//
//  SLAlertController.swift
//  ArchitectGenerics
//
//  Created by 姚胜龙 on 2017/7/5.
//  Copyright © 2017年 姚胜龙. All rights reserved.
//

import UIKit

//使用Builder设计模式自定义一个alert SLAlertController不能再外部实例化对象，只能在内部使用（否则没有意义）
class SLAlertController: NSObject {

    //不允许外部进行初始化
    private var params:BuilderParams?
    private init(params:BuilderParams) {
        super.init()
        self.params = params
    }

    //显示controller
    func showAlert() {
        let alert = UIAlertController(title: self.params?.title, message: self.params?.message, preferredStyle: UIAlertControllerStyle.alert)

        if self.params?.confirmTitle != nil {
            alert.addAction(UIAlertAction(title: self.params?.confirmTitle, style: UIAlertActionStyle.destructive, handler: self.params?.confirmHandle))

        }

        if self.params?.cancelTitle != nil {
            alert.addAction(UIAlertAction(title: self.params?.cancelTitle, style: UIAlertActionStyle.cancel, handler: self.params?.cancelHandle))
        }


        self.params?.context?.present(alert, animated: true) {

        }
    }

    //参数和构建的分离
    class BuilderParams: NSObject {

        //上下文,用AlertController
        var context:UIViewController?
        //alert 的提示标题
        var title:String?
        //alert 的提示信息
        var message:String?
        //确定按钮
        var confirmTitle:String?
        //取消按钮
        var cancelTitle:String?
        //确定回调
        var confirmHandle:((UIAlertAction) -> Swift.Void)?
        //取消回调
        var cancelHandle:((UIAlertAction) -> Swift.Void)?

        init(context:UIViewController) {
            super.init()
            self.context = context
        }
    }

    class Builder: NSObject {
        private var param:BuilderParams?

        init(context:UIViewController) {
            super.init()
            self.param = BuilderParams(context: context)
        }

        func setTitle(_ title:String) -> Builder {
            self.param?.title = title
            return self
        }
        func setMessage(_ message:String) -> Builder {
            self.param?.message = message
            return self
        }
        func setConfirmTitle(_ confirmTitle:String) -> Builder {
            self.param?.confirmTitle = confirmTitle
            return self
        }
        func setCancelTitle(_ cancelTitle:String) -> Builder {
            self.param?.cancelTitle = cancelTitle
            return self
        }
        func setConfirmHandle(_ confirmHandle: ((UIAlertAction) -> Swift.Void)? = nil) -> Builder {
            self.param?.confirmHandle = confirmHandle
            return self
        }
        func setCancelHandle (_ cancelHandle :((UIAlertAction) -> Swift.Void)? = nil) -> Builder {
            self.param?.cancelHandle = cancelHandle
            return self
        }

        //最后构建
        func build() -> SLAlertController {
            return SLAlertController(params: self.param!)
        }
    }
}
